package com.ekuaitu.kuaitustaff.activity;

import android.content.Context;
import android.os.Handler;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MyLocationConfiguration;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.map.UiSettings;
import com.baidu.mapapi.model.LatLng;
import com.ekuaitu.kuaitustaff.R;
import com.ekuaitu.kuaitustaff.api.ApiService;
import com.ekuaitu.kuaitustaff.api.ApiStore;
import com.ekuaitu.kuaitustaff.api.UrlConstant;
import com.ekuaitu.kuaitustaff.baiduMap.MapStatusUtils;
import com.ekuaitu.kuaitustaff.baiduMap.MarkerUtils;
import com.ekuaitu.kuaitustaff.base.BaseActivity;
import com.ekuaitu.kuaitustaff.bean.CarPositionYingYan;
import com.ekuaitu.kuaitustaff.utils.CheckRegexUtils;
import com.ekuaitu.kuaitustaff.utils.ToastUtils;

import org.json.JSONException;
import org.json.JSONObject;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

import static com.ekuaitu.kuaitustaff.activity.CarNewMainMapActivity.curPosition;

public class FindCarActivity extends BaseActivity {

    @BindView(R.id.tv_cancel)
    TextView tvCancel;
    @BindView(R.id.imageView_locate)
    ImageView imageViewLocate;
    private EditText edt_search;
    private LinearLayout linear_cancel;
    private Context mContext = this;
    private MapView mapView;
    private BaiduMap mBaiduMap;
    private MapStatusUtils mapStatusUtils;
    private MarkerUtils markerUtils;
    Handler handler = new Handler();
    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            handler.postDelayed(runnable, 15000);
            getCarPosition(licenseTag);
            //轮询的时候也更新自己定位
            MyLocationData locData = new MyLocationData.Builder()
                    .latitude(curPosition.latitude)
                    .longitude(curPosition.longitude).build();
            mBaiduMap.setMyLocationData(locData);
        }
    };
    private String licenseTag;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_find_car;
    }

    @Override
    protected void initView() {
        edt_search = (EditText) findViewById(R.id.edt_search);
        linear_cancel = (LinearLayout) findViewById(R.id.linear_cancel);

        edt_search.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (!TextUtils.isEmpty(s) && linear_cancel.getVisibility() == View.GONE) {
                    linear_cancel.setVisibility(View.VISIBLE);
                } else if (TextUtils.isEmpty(s)) {
                    linear_cancel.setVisibility(View.GONE);
                }
            }
        });
        edt_search.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    if (TextUtils.isEmpty(edt_search.getText().toString())) {
                        ToastUtils.makeText(mContext, "请输入要查询的车牌号", ToastUtils.LENGTH_SHORT).show();
                    } else {
                        if (CheckRegexUtils.isCarNum(edt_search.getText().toString())) {
                            licenseTag = edt_search.getText().toString();
                            handler.post(runnable);
                        } else {
                            dismissLoadingDialog();
                            ToastUtils.makeText(mContext, "请输入正确的车牌号", ToastUtils.LENGTH_SHORT).show();
                        }
                    }
                }
                return false;
            }
        });
    }

    @Override
    protected void initData() {
        initMap();
    }

    private void getCarPosition(String licenseTag) {
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("licenseTag", licenseTag);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), jsonObject.toString());
        new ApiStore().getRetrofit(UrlConstant.Request.BASE_URL_NEW, "", "").create(ApiService.class).getCarPosition(body).enqueue(new Callback<CarPositionYingYan>() {
            @Override
            public void onResponse(Call<CarPositionYingYan> call, Response<CarPositionYingYan> response) {
                if (response.isSuccessful() && response.body() != null) {
                    if (response.body().getStatus() == 200) {
                        if (response.body().getAttachment().getLatest_point() != null) {
                            mBaiduMap.clear();
                            markerUtils.showEndPositionIcon(mBaiduMap, new LatLng(response.body().getAttachment().getLatest_point().getLatitude(), response.body().getAttachment().getLatest_point().getLongitude()), 0, R.drawable.park_marker);
                            mapStatusUtils.animateMove(new LatLng(response.body().getAttachment().getLatest_point().getLatitude(), response.body().getAttachment().getLatest_point().getLongitude()), 16, 0);
                        }
                    }
                }
            }

            @Override
            public void onFailure(Call<CarPositionYingYan> call, Throwable t) {

            }
        });
    }

    //初始化地图
    public void initMap() {
        mapView = (MapView) findViewById(R.id.map_findCarActivity);
        mapView.showZoomControls(false);
        if (mBaiduMap == null) {
            mBaiduMap = mapView.getMap();
            // 设置不显示楼梯，开启定位图层
            mBaiduMap.setBuildingsEnabled(false);
            mBaiduMap.setMyLocationEnabled(true);
            mBaiduMap.setMyLocationConfiguration(new MyLocationConfiguration(
                    MyLocationConfiguration.LocationMode.NORMAL, true,
                    BitmapDescriptorFactory.fromResource(R.drawable.icon_mylocation), 0x00000000, 0x00000000));
            //设置地图交互
            UiSettings uiSettings = mBaiduMap.getUiSettings();
            uiSettings.setRotateGesturesEnabled(false);
            uiSettings.setOverlookingGesturesEnabled(false);
            uiSettings.setZoomGesturesEnabled(true);

            markerUtils = new MarkerUtils(mBaiduMap, mContext);
            mapStatusUtils = new MapStatusUtils(mBaiduMap, mContext);
            //设置自己的定位信息
            MyLocationData locData = new MyLocationData.Builder()
                    .latitude(curPosition.latitude)
                    .longitude(curPosition.longitude).build();
            mBaiduMap.setMyLocationData(locData);
            if (curPosition != null) {
                mapStatusUtils.animateMove(curPosition, 16, 600, 0);
            }
            mBaiduMap.setOnMarkerClickListener(new BaiduMap.OnMarkerClickListener() {
                @Override
                public boolean onMarkerClick(final Marker marker) {

                    return true;
                }
            });
        }
    }

    @OnClick({R.id.tv_cancel, R.id.imageView_locate})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_cancel:
                edt_search.setText("");
                linear_cancel.setVisibility(View.GONE);
                break;
            case R.id.imageView_locate:
                if (curPosition != null) {
                    mapStatusUtils.animateMove(curPosition, 16, 600, 0);
                } else {
                    ToastUtils.makeText(mContext, "正在定位...", ToastUtils.LENGTH_SHORT).show();
                }

                break;
        }
    }
}
